package com.sinosoft.common.util;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * List通用排序
 * 
 * @author unhappydepig
 * @mail yqw8912@163.com
 * @time 2015-5-22 上午10:32:07
 */
public class SortList<E> {
	/**
	 * List排序
	 * @param list
	 * @param method
	 */
	public static void Sort(List list, final String method) {
		Sort(list, method, null);
	}

	/**
	 * 排序
	 * @param list
	 * @param method
	 * @param sort
	 */
	public static void Sort(List list, final String method, final String sort) {
		Collections.sort(list, new Comparator() {
			public int compare(Object a, Object b) {
				int ret = 0;
				Object a_val = BeanUtil.getValue(a, method);
				Object b_val = BeanUtil.getValue(b, method);
				if (sort != null && "desc".equals(sort))// 倒序
				{
					ret = compareValue(b_val, a_val);
				} else// 正序
				{
					ret = compareValue(a_val, b_val);
				}
				return ret;
			}
		});
	}
	/**
	 * List排序
	 * @param a_val
	 * @param b_val
	 * @return
	 */
	public static int compareValue(Object a_val, Object b_val) {
		String className = a_val.getClass().getName();
		className = StringUtil.split(className, ".")[StringUtil.split(className, ".").length-1];
		if("Integer".equals(className)||"int".equals(className)){
			return compareInt(a_val, b_val);
		}
		if("Double".equals(className)||"double".equals(className)){
			return compareDouble(a_val, b_val);
		}		
		return a_val.toString().compareTo(b_val.toString());
	}

	/**
	 * int类型排序
	 * @param a_val
	 * @param b_val
	 * @return
	 */
	public static int compareInt(Object a_val,Object b_val){
		return Integer.parseInt(a_val.toString())-Integer.parseInt(b_val.toString());
	}
	/**
	 * double
	 * @param a_val
	 * @param b_val
	 * @return
	 */
	private static int compareDouble(Object a_val, Object b_val) {
		return (int)(Double.parseDouble(a_val.toString())-Double.parseDouble(b_val.toString()));
	}	
}
